import Input from "@/components/Input";
import { addFamily, updateFamily } from "@/services/Family";
import { Dialog, Form } from "@nutui/nutui-react-taro";
import { useRequest } from "taro-hooks";
import { showToast } from "@tarojs/taro";
import { useEffect } from "react";
import { useFamilyStore } from "@/model";

export default ({ info,open, onClose, refresh }) => {
  const id = info?.id;
  const {family,setFamily } = useFamilyStore();
  const [form] = Form.useForm();
  const { run } = useRequest(id ? updateFamily : addFamily, {
    manual: true,
    onSuccess: (res,[params]) => {
      onClose();
      refresh();
      if(params.id===family?.id){
        setFamily({
          ...(family||{}),
          ...params,
        })
      }
      showToast({
        title:(id?'编辑':'新增')+ "成功",
        icon:'none',
      });

    },
  });
  useEffect(() => {
    form.setFieldsValue(info);
  }, [open]);
  return (
    <Dialog
      title={id ? "编辑家庭" : "新增家庭"}
      visible={open}
      onConfirm={() => {
        form.submit();
      }}
      onCancel={() => {
        onClose();
      }}
    >
      <Form
        labelPosition="top"
        form={form}
        onFinish={(v) => {
          run({
            id: id!,
            name:v.name,
            description:v.description,
          });
        }}
      >
        <Form.Item
          label="名称"
          name="name"
          rules={[
            {
              required: true,
              message: "请输入家庭名称",
            },
          ]}
        >
          <Input placeholder="请输入" />
        </Form.Item>
        <Form.Item
          label="描述"
          name="description"
          rules={[
            {
              required: true,
            },
          ]}
        >
          <Input placeholder="请输入" />
        </Form.Item>
      </Form>
    </Dialog>
  );
};
